package swb.api.com.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import swb.api.com.repository.SysUserRepository;
import swb.api.com.repository.SysUserRoleRepository;
import swb.api.com.repository.dto.SysUser;
import swb.api.com.repository.dto.SysUserRole;
import swb.api.com.repository.dto.UserInfo;
import swb.api.com.service.SysUserService;
import swb.api.com.vo.req.AdminCreateRequest;

import java.math.BigDecimal;
import java.time.LocalDateTime;

@Service
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserRepository sysUserRepository;

    @Autowired
    private SysUserRoleRepository sysUserRoleRepository;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public Page<UserInfo> findAll(Pageable pageable) {
        // 这里需要根据实际业务实现用户信息查询逻辑
        // 暂时返回空实现，需要根据UserInfo实体和业务需求完善
        return null;
    }

    @Override
    public void updateBalance(Long id, BigDecimal newBalance) {
        // 实现余额更新逻辑
        // 需要根据实际的用户余额字段和业务逻辑实现
    }

    @Override
    public SysUser findByUsername(String username) {
        return sysUserRepository.findByUsername(username);
    }

    @Override
    @Transactional
    public void createAdmin(AdminCreateRequest adminCreateRequest) {
        // 检查用户名是否已存在
        if (sysUserRepository.existsByUsername(adminCreateRequest.getUsername())) {
            throw new RuntimeException("用户名已存在");
        }

        // 创建管理员用户
        SysUser user = new SysUser();
        user.setUsername(adminCreateRequest.getUsername());
        user.setPassword(passwordEncoder.encode(adminCreateRequest.getPassword()));
        user.setNickname(adminCreateRequest.getNickname());
        user.setEmail(adminCreateRequest.getEmail());
        user.setMobile(adminCreateRequest.getMobile());
        user.setStatus(1); // 默认启用
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());

        // 保存用户
        user = sysUserRepository.save(user);

        // 分配管理员角色（假设角色ID为1）
        SysUserRole userRole = new SysUserRole();
        userRole.setUserId(user.getId());
        userRole.setRoleId(1L);
        sysUserRoleRepository.save(userRole);
    }

    @Override
    public void saveUserRole(SysUserRole sysUserRole) {
        sysUserRoleRepository.save(sysUserRole);
    }

    @Override
    public void save(SysUser user) {
        sysUserRepository.save(user);
    }
}
